﻿using Blm.VisionCloud.FrameWork.Cached;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Utility;

namespace VisionCloud.Web.Middleware
{
    public class SurfaceUpdateMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ICached cached;
        private int downloadcount = 30;
        private string add_key = "surface_update_";

        public SurfaceUpdateMiddleware(RequestDelegate next, IConfiguration config, ICached cached)
        {
            this.next = next;
            this.cached = cached;
            downloadcount = config.GetSection("SurefaceUpdaeCount").Get<int>();
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (CheckDownloadCount(out string key))
                {
                    await next(context);
                    cached.Remove(key);
                    return;
                }
            }
            catch (Exception ex)
            {
                Logger.Info($"SurfaceUpdateMiddleware：ex" + JsonConvert.SerializeObject(ex));
            }
            ApiResult result = new ApiResult()
            {
                Code = AjaxCode.Error,
                Message = StartupServer.CommonLocalizer["YB0155"].Value //下载量过多，请稍等再试
            };
            context.Response.StatusCode = 444;
        }

        public bool CheckDownloadCount(out string key)
        {
            key = string.Empty;
            int count = 0;
            for (int i = 0; i < downloadcount; i++)
            {
                key = $"{add_key}{i}";
                var dc = cached.Get<DownloadCache>(key);
                if (dc != null)
                {
                    count++;
                }
                else
                {
                    key = $"{add_key}{count}";
                    dc = new DownloadCache()
                    {
                        Key = key,
                        CacheTime = DateTime.Now
                    };
                    cached.Set<DownloadCache>(key, dc, TimeSpan.FromSeconds(20));
                    return true;
                }
            }
            return false;
        }
    }

    public class DownloadCache
    {
        public string Key { get; set; }
        public DateTime CacheTime { get; set; }
    }
}